package cn.edu.niit.studyspace.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.lang.ref.WeakReference;
import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.bean.Course;

public class CourseSelectAdapter extends RecyclerView.Adapter<CourseSelectAdapter.ViewHolder>
    implements View.OnClickListener {

  private WeakReference<Context> wrContext;
  private List<Course> courses;
  private OnItemClick onItemClick;

  public CourseSelectAdapter(Context context, List<Course> courses, OnItemClick onItemClick) {
    this.wrContext = new WeakReference<>(context);
    this.courses = courses;
    this.onItemClick = onItemClick;
  }

  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view =
        LayoutInflater.from(wrContext.get()).inflate(R.layout.item_course_select, parent, false);
    view.setOnClickListener(this);
    return new ViewHolder(view);
  }

  @Override
  public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    Course course = courses.get(position);
    holder.itemView.setTag(position);
    holder.name.setText(course.getName());
    holder.teacher.setText(course.getTeacher());
  }

  @Override
  public int getItemCount() {
    return courses.size();
  }

  public void notifyData(List<Course> courses) {
    this.courses = courses;
    notifyDataSetChanged();
  }

  @Override
  public void onClick(View v) {
    // 接口实现
    onItemClick.onItemClick(v, (int) v.getTag());
  }

  /** 定义一个接口用于Item点击 */
  public interface OnItemClick {
    void onItemClick(View view, int position);
  }

  static class ViewHolder extends RecyclerView.ViewHolder {
    TextView name;
    TextView teacher;

    public ViewHolder(@NonNull View itemView) {
      super(itemView);
      teacher = itemView.findViewById(R.id.tv_item_select_course_teacher);
      name = itemView.findViewById(R.id.tv_item_select_course_name);
    }
  }
}
